package jwtauth

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/spf13/viper"
	"gpt-api/framework/auther"
	"gpt-api/framework/cache"
)

// InitJWTAuth 初始化用户认证
func InitJWTAuth(store cache.Store) (auther.Auther, error) {
	var opts []Option
	opts = append(opts, SetExpired(viper.GetInt("auth.expired")))
	opts = append(opts, SetSigningKey([]byte(viper.GetString("auth.signing_key"))))
	opts = append(opts, SetKeyfunc(func(t *jwt.Token) (interface{}, error) {
		if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, auther.ErrInvalidToken
		}
		return []byte(viper.GetString("auth.signing_key")), nil
	}))
	signMethod := "HS256"
	switch signMethod {
	case "HS256":
		opts = append(opts, SetSigningMethod(jwt.SigningMethodHS256))
	case "HS384":
		opts = append(opts, SetSigningMethod(jwt.SigningMethodHS384))
	case "HS512":
		opts = append(opts, SetSigningMethod(jwt.SigningMethodHS512))
	}

	return New(NewStorer(store), opts...), nil
}
